package table

import (
	"encoding/json"
	"fmt"
	"strings"

	"gitee.com/linxing_3/sr-core/yal/ystr"
	"gitee.com/linxing_3/sr-core/yerr"
	"gitee.com/mkwchecking/sr-admin/apps/devtools/entity"
	"gitee.com/mkwchecking/sr-admin/apps/devtools/service"

	"github.com/spf13/cobra"
)

// tableCmd
var (
	tableCmd = &cobra.Command{
		Use:     "table",
		Short:   "[Devtools] table command",
		PreRunE: dependsCheck,
		Run: func(cmd *cobra.Command, args []string) {
			cmd.Help()
		},
	}
	svc        *service.DevtoolsSvc
	svcBuilder func(cfg string) (*service.DevtoolsSvc, error)
)

func GetTableCmd(svc func(cfg string) (*service.DevtoolsSvc, error)) *cobra.Command {
	svcBuilder = svc
	return tableCmd
}

func dependsCheck(cmd *cobra.Command, args []string) error {
	if svc == nil {
		// tableArg.Parse(cmd)
		cfg, err := cmd.Flags().GetString("config")
		if err != nil {
			return err
		} else if cfg == "" {
			return yerr.ErrBizParamInvalid.Errorf("arg (-c/--config $CONFIG_PATH) is required")
		}
		svc, err = svcBuilder(cfg)
		return err
	}
	return nil
}

func PrintAsTable(t *entity.ModuleTable, head ...bool) {

	colMap := map[string]struct {
		Title string
		Len   int
	}{
		"domain": {
			Title: "Domain",
			Len:   10,
		},
		"className": {
			Title: "Table name  ",
			Len:   20,
		},
		"comment": {
			Title: "Comment  ",
			Len:   30,
		},
	}

	// 字段分割符
	colSplitter := "| "
	// 边框分隔符
	borderItem := "="

	border := strings.Join([]string{
		borderItem,
		strings.Repeat(borderItem, colMap["domain"].Len),
		strings.Repeat(borderItem, colMap["className"].Len),
		strings.Repeat(borderItem, colMap["comment"].Len),
	}, borderItem)

	if len(head) > 0 && head[0] {
		headRow := []string{
			"",
			ystr.PadRightSpace(colMap["domain"].Title, colMap["domain"].Len),
			ystr.PadRightSpace(colMap["className"].Title, colMap["className"].Len),
			ystr.PadRightSpace(colMap["comment"].Title, colMap["comment"].Len),
		}
		fmt.Println(border)
		fmt.Println(strings.Join(headRow, colSplitter))
		fmt.Println(border)
		fmt.Println(border)
	}

	row := []string{
		"",
		ystr.PadRightSpace(t.Domain, colMap["domain"].Len),
		ystr.PadRightSpace(t.ClassName, colMap["className"].Len),
		ystr.PadRightSpace(t.Comment, colMap["comment"].Len),
	}

	fmt.Println(strings.Join(row, colSplitter))

	if len(head) > 1 && head[1] {
		fmt.Println(border)
	}
}

func PrintAsJson(t *entity.ModuleTable, head ...bool) {
	bts, err := json.MarshalIndent(t, "", "  ")
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(bts))
}
